﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using Auktionshuset.UserControls;

namespace Auktionshuset
{
    public partial class MainWindow
    {
        private readonly Dictionary<int, AuctionWindow> _auctionWindows = new Dictionary<int, AuctionWindow>();

        private List<Auction> _auctions;
        private readonly Connection _conn;

        public MainWindow(Connection conn)
        {
            _conn = conn;
            conn.AuctionWindows = _auctionWindows;

            InitializeComponent();

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;

            AuctionListView.Loading = true;
            worker.RunWorkerAsync();
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            _auctions = _conn.GetAuctions();
        }
        
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            AuctionListView.Loading = false;
            
            foreach (Auction auction in _auctions)
            {
                AuctionListViewItem alvi = new AuctionListViewItem(auction);
                alvi.Click += Auction_Click;
                AuctionListView.Items.Add(alvi);
            }

            _conn.AuctionPosted += OnAuctionPosted;
            _conn.Start();
        }

        private void OnAuctionPosted(Auction auction)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                AuctionListViewItem alvi = new AuctionListViewItem(auction);
                alvi.Click += Auction_Click;
                AuctionListView.Items.Add(alvi);
            }));
        }

        void Auction_Click(object sender, EventArgs e)
        {
            AuctionListViewItem alvi = (AuctionListViewItem) sender;
            AuctionWindow aw = new AuctionWindow(_conn, alvi.Auction) { Owner = this };
            aw.Show();
            _conn.SubscribeToAuction(aw);
        }

        private void BtnNyAuktion_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            CreateAuctionWindow newWindow = new CreateAuctionWindow(_conn) { Owner = this };
            newWindow.ShowDialog();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            _conn.Logout();
            _conn.Stop();
        }
    }
}
